var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var proRouter = require('./routes/pro');
var cartRouter = require('./routes/cart');
var orderRouter = require('./routes/order');
var userRouter = require('./routes/user');
var bannerRouter = require('./routes/banner');
var addressRouter = require('./routes/address');
var loginRouter = require('./routes/login');

var proApiRouter = require("./api/pro")
var bannerApiRouter = require("./api/banner")
var userApiRouter = require("./api/user")
var cartApiRouter = require("./api/cart")
var orderApiRouter = require("./api/order")
var searchApiRouter = require("./api/search")

const multer = require("multer");
const upload = multer({ dest: 'public/uploads' })

const session = require("express-session")


var app = express();

// 后端设置cors解决跨域方案
app.all("*",(req,res,next)=>{
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,token");
  next()
})


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(upload.any())

// 接口路由
app.use('/api/pro', proApiRouter);
app.use('/api/banner', bannerApiRouter);
app.use('/api/user', userApiRouter);
app.use('/api/cart', cartApiRouter);
app.use('/api/order', orderApiRouter);
app.use('/api/search', searchApiRouter);

// "ok"
// 时间戳
// 随机数
// hello world

// 注册session
app.use(session({
  secret: '千锋H5，前端界的扛把子',   // 加密信息，可以随便写
  resave: false,      // 强制保存session，默认为true，建议设置为false
  saveUninitialized: true,    // 强制将未初始化的session存储，默认为true，建议为true
  cookie: { maxAge: 1000 * 60 * 60 }    // 过期时间，毫秒数
}))

// 登录守卫
app.all("*", (req, res, next)=>{
  // 所有的页面模板路由（除了登录和登录处理），需要添加守卫
  if(!req.url.startsWith("/login")){
    // 先判断登录状态是否正确
    // if(req.cookies.isLogin === "ok"){    // 使用cookie
    if(req.session.isLogin === "ok"){     // 使用session
      // 正确，放过
      next();
    }else{
      // 不正确，跳转到登录
      res.redirect("/login");
    }
  }else{
    // 如果路由是登录或登录处理，放过
    next();
  }
})

app.use('/', indexRouter);
app.use('/pro', proRouter);
app.use('/address', addressRouter);
app.use('/cart', cartRouter);
app.use('/order', orderRouter);
app.use('/user', userRouter);
app.use('/banner', bannerRouter);
app.use('/login', loginRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
